package ch.nortgram.countdown_worldcup_2014.fragment;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.xml.sax.SAXException;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import ch.nortgram.countdown_worldcup_2014.R;
import ch.nortgram.countdown_worldcup_2014.rss.Feed;
import ch.nortgram.countdown_worldcup_2014.rss.Item;
import ch.nortgram.countdown_worldcup_2014.rss.NewsArrayAdapter;
import ch.nortgram.countdown_worldcup_2014.rss.Reader;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class NewsFragment extends ListFragment
	{
	private String news_categorie[][] = new String[2][];
	private String news[][] = new String[4][];
	private String news_title[], news_desc[], news_img[],news_link[];
	private ArrayList<Item> rssItems;
	private int categorie_pos;
	TextView categorie_title;
	View news_view;
    

	public NewsFragment()
    	{
        super();
    	}
	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    	{
    	news_view = inflater.inflate(R.layout.activity_news, container, false);
		
    	news_categorie[0] = getResources().getStringArray(R.array.news_feed_url);
    	news_categorie[1] = getResources().getStringArray(R.array.news_feed_desc);
    	
        categorie_title = (TextView)news_view.findViewById(R.id.news_categorie);
    	return news_view;
    	}
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    	{
        super.onCreate(savedInstanceState);
        }

    @Override
    public void onStart()
    	{
        super.onStart();
        // inizialisiere imageloader
        if(!ImageLoader.getInstance().isInited())
        	{
        	DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
        		.cacheInMemory()
        		.cacheOnDisc()
        		.build();
        	ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity())
				.defaultDisplayImageOptions(defaultOptions)
				.discCacheFileCount(150)
				.build();
        	ImageLoader.getInstance().init(config);
        	}
        //
        
        categorie_pos = 0;
        
        new LoadNews().execute(news_categorie[0][categorie_pos]);
        
        categorie_title.setText(news_categorie[1][categorie_pos]);
        
        ImageView btn_categorie_right = (ImageView)news_view.findViewById(R.id.news_categorie_right);
        btn_categorie_right.setOnClickListener(new OnClickListener()
        		{
				@Override
				public void onClick(View v)
					{
					if(categorie_pos<news_categorie[0].length-1)
						{
						categorie_pos++;
						new LoadNews().execute(news_categorie[0][categorie_pos]);
				        categorie_title.setText(news_categorie[1][categorie_pos]);
						}
					else
						{
						Log.e("","endoflist");
						}
					}
				});
        ImageView btn_categorie_left = (ImageView)news_view.findViewById(R.id.news_categorie_left);
        btn_categorie_left.setOnClickListener(new OnClickListener()
        		{
				@Override
				public void onClick(View v)
					{
					if(categorie_pos>0)
						{
						categorie_pos--;
						new LoadNews().execute(news_categorie[0][categorie_pos]);
				        categorie_title.setText(news_categorie[1][categorie_pos]);
						}
					else
						{
						Log.e("","endoflist");
						}
					}
				});
    	}

    @Override
	public void onListItemClick(ListView l, View v, int pos, long id)
    	{  
        super.onListItemClick(l, v, pos, id);
        // AlertDialog
        Intent browser_intent = new Intent(Intent.ACTION_VIEW);
        browser_intent.setData(Uri.parse(rssItems.get(pos).getLink()));
        startActivity(browser_intent);
        }

    
    private class LoadNews extends AsyncTask<String, Void, Boolean>
    	{

        @Override
        protected Boolean doInBackground(String... params)
        	{
            URL url;
            Feed feed = null;
    		try {
    			url = new URL(params[0]);
    			feed = Reader.read(url);
    			}
    		catch (MalformedURLException e) {e.printStackTrace();}
    		catch (SAXException e){return false;}
    		catch (IOException e) {return false;}

            rssItems = feed.getItems();
            
            news_title	= new String[rssItems.size()+1];
            news_desc	= new String[rssItems.size()+1];
            news_img	= new String[rssItems.size()+1];
            news_link	= new String[rssItems.size()+1];
            
            int i=0;
            for(Item rssItem : rssItems)
            	{
            	news_title[i] = rssItem.getTitle();
            	news_desc[i] = rssItem.getDescription();
            	news_img[i] = rssItem.getImage();
            	news_link[i] = rssItem.getLink();
            	i++;
            	}
            news[0] = news_title;
            news[1] = news_desc;
            news[2] = news_img;
            news[3] = news_link;
        	return true;
        	}

        @Override
        protected void onPostExecute(Boolean result)
        	{
        	if(result)
        		{
        		Log.e("","gooood");
        		setListAdapter(new NewsArrayAdapter(getActivity(),R.layout.activity_news_row,news));
        		}
        	else
        		{
        		Log.e("","problem");
        		Toast.makeText(getActivity(), "network problem", Toast.LENGTH_SHORT).show();
        		}
        	}

        @Override
        protected void onPreExecute()
        	{
        	}
    	}
    
    @Override
	public void onDestroy()
    	{
    	super.onDestroy();
    	}
	}